#include <winsock2.h>
#include "msn.h"
#pragma comment(lib, "ws2_32.lib")

dkim::msn::msn(dkim::Debug* debug)
:trialId_(0), debug_(debug)
{
	WORD wVersionRequested = MAKEWORD(2, 2);
	WSADATA wsaData;
	WSAStartup(wVersionRequested, &wsaData);
	debug_->putString("DKIM: Start class", dkim::MessageType::notice);
}

dkim::msn::~msn()
{
	WSACleanup();
}

unsigned long dkim::msn::domainToAddr(std::string domain)
{
	hostent *host;
	host = gethostbyname(domain.c_str());
	std::string message = "DKIM: ";
	long int *add = (long int*)*host->h_addr_list;
	in_addr inAddr;
	inAddr.s_addr =*add;
	debug_->putString(message + domain + "/" + inet_ntoa(inAddr),
		dkim::MessageType::notice);
	return inet_addr(inet_ntoa(inAddr));
}

SOCKET dkim::msn::getSocket()
{
	debug_->putString("DKIM: getSocket", dkim::MessageType::notice);
	return socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
}

void dkim::msn::closeSocket(SOCKET socket)
{
	debug_->putString("DKIM: close socket.", dkim::MessageType::notice);
	closesocket(socket);
}

void dkim::msn::connectByDomain(SOCKET socket, std::string domain,
								unsigned short port)
{
	sockaddr_in ServerAddr;
	ServerAddr.sin_family = AF_INET;
	ServerAddr.sin_addr.s_addr = domainToAddr(domain);
	ServerAddr.sin_port = htons(port);
	connect(socket, (sockaddr *)&ServerAddr, sizeof(ServerAddr));
	debug_->putString("DKIM: connect by " + domain, dkim::MessageType::notice);
}

void dkim::msn::connectByIp(SOCKET socket, std::string ip,
							unsigned short port)
{
	sockaddr_in ServerAddr;
	ServerAddr.sin_family = AF_INET;
	ServerAddr.sin_addr.s_addr = inet_addr(ip.c_str());
	ServerAddr.sin_port = htons(port);
	connect(socket, (sockaddr *)&ServerAddr, sizeof(ServerAddr));
	debug_->putString("DKIM: connect by " + ip, dkim::MessageType::notice);
}

void dkim::msn::putServer(SOCKET socket, std::string message)
{
	send(socket, message.c_str(), message.length(), 0);
	debug_->putString("DKIM: " + message, dkim::MessageType::client);
}

std::string dkim::msn::getServer(SOCKET socket)
{
	char data[20000];
	int recieve = recv(socket, data, sizeof(data) - 1, 0);
	data[recieve] = '\0';
	std::string message = std::string(data, strlen(data));
	debug_->putString("DKIM: " + message, dkim::MessageType::server);
	return message;
}
